#include "PhysicSystem.h"

PhysicSystem::PhysicSystem(){};
PhysicSystem::~PhysicSystem(){};

int PhysicSystem::Initialize(){

	return 0;
};

int PhysicSystem::Update(float a_timePassed){
	int t_size = m_RigidBodyList.Get_Size();
	for(int i = 0; i < t_size; i++){
		PhysicRigidBody *a_RigidBody = m_RigidBodyList.Get_Data(i);
		m_PhysicCollisionResolution.Update(a_RigidBody, a_timePassed);
		m_PhysicCollisionDetection.Update(a_RigidBody, &m_RigidBodyList);
	}
	return 0;
};

void PhysicSystem::Release(){
	int t_size = m_RigidBodyList.Get_Size();
	for(int i = 0; i < t_size; i++){
		m_RigidBodyList.Get_Data(i)->Release();
	}
	m_RigidBodyList.Clear();
};

void PhysicSystem::Create(PhysicObject *a_PhysicObject){
	Destroy(a_PhysicObject);
	PhysicRigidBody *t_PhysicRigidBody = new PhysicRigidBody(a_PhysicObject);
	m_RigidBodyList.Insert_ToEnd(t_PhysicRigidBody);
	//t_PhysicRigidBody = 0;
};

void PhysicSystem::Destroy(PhysicObject *a_PhysicObject){
	int t_size = m_RigidBodyList.Get_Size();
	for(int i = 0; i < t_size; i++){
		PhysicRigidBody *t_PhysicRigidBody = m_RigidBodyList.Get_Data(i);
		if(a_PhysicObject == t_PhysicRigidBody->m_PhysicObject){
			for(int j = 0; j < t_size; j++){
				PhysicRigidBody *t_PhysicRigidBody_2 = m_RigidBodyList.Get_Data(j);
				if(t_PhysicRigidBody == t_PhysicRigidBody_2){
					continue;
				}
				int t_sizeOfRigidBodyContact = t_PhysicRigidBody_2->m_PhysicRigidBodyContactList.Get_Size();
				for(int k = 0; k < t_sizeOfRigidBodyContact; k++){
					PhysicRigidBody *t_PhysicRigidBodyToRemove = (t_PhysicRigidBody_2->m_PhysicRigidBodyContactList.Get_Data(k));
					if(t_PhysicRigidBody == t_PhysicRigidBodyToRemove){
						t_PhysicRigidBody_2->m_PhysicRigidBodyContactList.Remove_FromIndexPtr(k);
						break;
					}
				}
				int t_sizeOfPhysicBodyContact = t_PhysicRigidBody_2->m_PhysicObject->m_PhysicObjectContactList.Get_Size();
				for(int k = 0; k < t_sizeOfPhysicBodyContact; k++){
					PhysicObject *t_PhysicObjectToRemove = (*t_PhysicRigidBody_2->m_PhysicObject->m_PhysicObjectContactList.Get_Data(k));
					if(t_PhysicRigidBody->m_PhysicObject == t_PhysicObjectToRemove){
						t_PhysicRigidBody_2->m_PhysicObject->m_PhysicObjectContactList.Remove_FromIndexPtr(k);
						break;
					}
				}
				t_PhysicRigidBody_2 = 0;
			}
			t_PhysicRigidBody->Release();
			m_RigidBodyList.Remove_FromIndex(i);
			break;
		}
	}
};
